//
//  InitTabBar.swift
//  sinaWeiBo
//
//  Created by Xuwei Yang on 16/8/8.
//  Copyright © 2016年 Xuwei Yang. All rights reserved.
//

import UIKit

// 继承 NSObjectProtocol,可以使用weak,进行弱引用修饰
protocol YMMTabBarDelegate: NSObjectProtocol{

    func didSelectedComposeButton()
}

class InitTabBar: UITabBar {

    //按钮的闭包
    var composeButtonClosure: (()->())?
    //定义代理对象
    weak var YMMDelegate:YMMTabBarDelegate?
    
    //MARK:--懒加载
    private lazy var composeButton: UIButton = {
    
        let button = UIButton()
        
        //添加点击事件
        button.addTarget(self, action: #selector(InitTabBar.composeButtonAction), forControlEvents: .TouchUpInside)
        
        //设置按钮背景
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        
        //指定大小
        button.sizeToFit()
        return button
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    
    
    //添加视图
    private func setupUI() {
        addSubview(composeButton)
    }
    
    // MARK: --点击事件
    
    @objc func composeButtonAction() {
    
        //执行
        composeButtonClosure?()
        YMMDelegate?.didSelectedComposeButton()
    }
    

    //调整子控件的布局
    override func layoutSubviews() {
        super.layoutSubviews()
        composeButton.center.x = frame.size.width * 0.5
        composeButton.center.y = frame.size.height * 0.5
        
        let itemWidth = frame.size.width / 5
        //
        var index = 0
        //
        for value in subviews {
            
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                //
                value.frame.size.width = itemWidth
                value.frame.origin.x = CGFloat(index) * itemWidth
                index += 1
                
                if index == 2 {
                
                    index += 1
                }
            }
        }
}

}


